//package com.ruoyi.electronicFence.task;
//
//import com.ruoyi.electronicFence.domain.TDeviceStatus;
//import com.ruoyi.electronicFence.service.ITDeviceStatusService;
//import com.ruoyi.electronicFence.service.ITEfAlarmService;
//import org.apache.http.HeaderElement;
//import org.apache.http.HeaderElementIterator;
//import org.apache.http.HttpResponse;
//import org.apache.http.client.methods.CloseableHttpResponse;
//import org.apache.http.client.methods.HttpGet;
//import org.apache.http.impl.client.CloseableHttpClient;
//import org.apache.http.impl.client.HttpClients;
//import org.apache.http.conn.ConnectionKeepAliveStrategy;
//import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
//import org.apache.http.message.BasicHeaderElementIterator;
//import org.apache.http.protocol.HTTP;
//import org.apache.http.protocol.HttpContext;
//import org.apache.http.util.EntityUtils;
//import org.springframework.stereotype.Component;
//
//import javax.annotation.PostConstruct;
//import java.io.IOException;
//import java.net.URI;
//import java.time.LocalDateTime;
//import java.time.format.DateTimeFormatter;
//import java.util.ArrayList;
//import java.util.List;
//import java.util.concurrent.ExecutorService;
//import java.util.concurrent.Executors;
///*
//长连接获取工控报警信息
// */
//@Component
//public class LongConnectionEvent {
//
//    private final ExecutorService executorService;
//    private final PoolingHttpClientConnectionManager connectionManager;
//    private final CloseableHttpClient httpClient;
//    private final ITEfAlarmService iTEfAlarmService;
//    private final ITDeviceStatusService iTDeviceStatusService;
//
//    public LongConnectionEvent(ITEfAlarmService iTEfAlarmService,ITDeviceStatusService iTDeviceStatusService) {
//        this.iTEfAlarmService = iTEfAlarmService; //
//        this.iTDeviceStatusService = iTDeviceStatusService;
//        List<TDeviceStatus> tDeviceStatuses = iTDeviceStatusService.selectTDeviceStatusList(new TDeviceStatus());
//        this.executorService = Executors.newFixedThreadPool(tDeviceStatuses.size()); // 设置同时处理连接的格数
//        this.connectionManager = new PoolingHttpClientConnectionManager();
//        // 设置最大连接数
//        connectionManager.setMaxTotal(100);
//        // 设置每个路由的最大连接数
//        connectionManager.setDefaultMaxPerRoute(10);
//
//        // 创建 HttpClient 对象
//        this.httpClient = HttpClients.custom()
//                .setConnectionManager(connectionManager)
//                .setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
//                    // 设置保持连接的时间
//                    @Override
//                    public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
//                        HeaderElementIterator it = new BasicHeaderElementIterator(
//                                response.headerIterator(HTTP.CONN_KEEP_ALIVE));
//                        while (it.hasNext()) {
//                            HeaderElement he = it.nextElement();
//                            String param = he.getName();
//                            String value = he.getValue();
//                            if (value != null && param.equalsIgnoreCase("timeout")) {
//                                try {
//                                    return Long.parseLong(value) * 1000;
//                                } catch (NumberFormatException ignore) {
//                                }
//                            }
//                        }
//                        return 60 * 1000; // 默认保持连接60秒
//                    }
//                })
//                .build();
//    }
//
////    @PostConstruct
//    public void initializeLongConnections() {
//        List<TDeviceStatus> tDeviceStatuses = iTDeviceStatusService.selectTDeviceStatusList(new TDeviceStatus());
//        // 创建一个 List 用来存储构建好的 URL
//        List<String> urls = new ArrayList<>();
//
//// 遍历设备状态列表
//        for (TDeviceStatus device : tDeviceStatuses) {
//            String deviceIp = device.getDeviceIp();
//
//            // 构建 URL 并添加到列表中
//            String serverUrl = "http://" + deviceIp + ":8080/electronicFence/receive-alarm-data";
//            urls.add(serverUrl);
//        }
//
//// 将 List 转换为数组
//        String[] serverUrls = urls.toArray(new String[0]);
//
//
////        // 定义服务器URL列表
////        String[] serverUrls = {
////                "http://192.168.3.43:8080/electronicFence/receive-alarm-data",
////                "http://192.168.3.44:8080/electronicFence/receive-alarm-data",
////                "http://192.168.3.45:8080/electronicFence/receive-alarm-data",
////                "http://192.168.3.46:8080/electronicFence/receive-alarm-data",
////                "http://192.168.3.47:8080/electronicFence/receive-alarm-data"
////        };
//
//        // 提交任务到线程池
//        for (String serverUrl : serverUrls) {
//            executorService.submit(() -> {
//                try {
//                    // 创建 GET 请求
//                    HttpGet httpGet = new HttpGet(serverUrl);
//
//                    // 添加保持连接的头
//                    httpGet.setHeader("Connection", "keep-alive");
//
//                    // 添加其他必要的请求头
//                    httpGet.setHeader("Content-Type", "application/json");
//                    httpGet.setHeader("Accept", "*/*");
//                    httpGet.setHeader("Host", serverUrls+":8080"); // 这里应该根据实际URL设置Host
//
//                    // 构建当前时间并添加到URL中
//                    LocalDateTime now = LocalDateTime.now();
//                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//                    String formattedDateTime = now.format(formatter);
//                    httpGet.setURI(new URI(httpGet.getURI().toString() + "?dataTime=" + formattedDateTime));
//
//                    // 发送请求并获取响应
//                    try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
//                        // 处理响应
//                        System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
//                        // 读取响应体
//                        String responseBody = EntityUtils.toString(response.getEntity());
//                        System.out.println("Response Body : " + responseBody);
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            });
//        }
//
//        // 注册一个关闭钩子
//        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
//            try {
//                httpClient.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            executorService.shutdownNow();
//        }));
//    }
//}
